package com.dalei.vdsmanager.management.system.action;

import java.util.Date;
import java.util.List;
import java.util.Map;

import com.dalei.vdsmanager.security.dao.User;
import com.dalei.vdsmanager.security.service.UserService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class AddUserAction extends ActionSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = 781545609773535439L;

	private UserService userService;

	private String userName;

	private String password;

	private String repeatPassword;

	private List<Integer> roleIds;

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getRepeatPassword() {
		return repeatPassword;
	}

	public void setRepeatPassword(String repeatPassword) {
		this.repeatPassword = repeatPassword;
	}

	public List<Integer> getRoleIds() {
		return roleIds;
	}

	public void setRoleIds(List<Integer> roleIds) {
		this.roleIds = roleIds;
	}

	@Override
	public String execute() throws Exception {
		// TODO Auto-generated method stub
		// return super.execute();
		Map<String, Object> session = ActionContext.getContext().getSession();
		String lastName = (String) session.get("SPRING_SECURITY_LAST_USERNAME");
		User u = userService.getUserByUserName(lastName);
		if (u != null) {
			Date createdTime = new Date();
			userService.addUser(userName, password, true, u, createdTime,
					roleIds);
			return SUCCESS;
		} else {
			return ERROR;
		}
	}

	@Override
	public void validate() {
		// TODO Auto-generated method stub
		super.validate();
		clearFieldErrors();
		if (userName == null) {
			addFieldError("userName", getText("addUser.userName.null"));
		} else {
			userName = userName.trim();
			if ((userName.length() == 0) || (userName.length() > 64)) {
				addFieldError("userName", getText("addUser.userName.invalid"));
			} else {
				if (userService.checkRepeat(userName)) {
					addFieldError("userName",
							getText("addUser.userName.existed"));
				}
			}
		}
		if (password == null) {
			addFieldError("password", getText("addUser.password.null"));
		}
		if (repeatPassword == null) {
			addFieldError("repeatPassword",
					getText("addUser.repeatPassword.null"));
		} else {
			if (!repeatPassword.equals(password)) {
				addFieldError("repeatPassword",
						getText("addUser.repeatPassword.notMatch"));
			}
		}
		if (roleIds == null) {
			addFieldError("roleIds", getText("addUser.roleIds.null"));
		}
	}
}
